package cn.iocoder.yudao.module.lfd.service.customer;

import cn.hutool.core.util.RandomUtil;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.pojo.SocialUserEvent;
import cn.iocoder.yudao.module.system.api.oauth2.OAuth2TokenApi;
import cn.iocoder.yudao.module.system.api.oauth2.dto.OAuth2AccessTokenCreateReqDTO;
import cn.iocoder.yudao.module.system.api.oauth2.dto.OAuth2AccessTokenRespDTO;
import cn.iocoder.yudao.module.system.enums.oauth2.OAuth2ClientConstants;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.math.BigDecimal;
import java.util.*;

import cn.iocoder.yudao.module.lfd.controller.admin.customer.vo.*;
import cn.iocoder.yudao.module.lfd.dal.dataobject.customer.CustomerDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.lfd.convert.customer.CustomerConvert;
import cn.iocoder.yudao.module.lfd.dal.mysql.customer.CustomerMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.lfd.enums.ErrorCodeConstants.CUSTOMER_NOT_EXISTS;

/**
 * 顾客 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class CustomerService {


    @Resource
    private CustomerMapper customerMapper;

    @EventListener
    public void createCustomer(SocialUserEvent socialUserEvent) {
        CustomerDO customerDO = customerMapper.selectById(socialUserEvent.getUserId());
        if (customerDO != null) return;
        CustomerDO customer = new CustomerDO()
                .setId(socialUserEvent.getUserId())
                .setMoney(BigDecimal.ZERO).setIntegral(0D)
                .setOpenid(socialUserEvent.getOpenid())
                .setNickName("昵称" + RandomUtil.randomNumbers(4))
                .setPhone(socialUserEvent.getPhone())
                .setAvatar(socialUserEvent.getAvatar());
        customerMapper.insert(customer);
    }

    
    public Long createCustomer(CustomerCreateReqVO createReqVO) {
        // 插入
        CustomerDO customer = CustomerConvert.INSTANCE.convert(createReqVO);
        customerMapper.insert(customer);
        // 返回
        return customer.getId();
    }

    
    public void updateCustomer(CustomerUpdateReqVO updateReqVO) {
        // 校验存在
        validateCustomerExists(updateReqVO.getId());
        // 更新
        CustomerDO updateObj = CustomerConvert.INSTANCE.convert(updateReqVO);
        customerMapper.updateById(updateObj);
    }

    
    public void deleteCustomer(Long id) {
        // 校验存在
        validateCustomerExists(id);
        // 删除
        customerMapper.deleteById(id);
    }

    private void validateCustomerExists(Long id) {
        if (customerMapper.selectById(id) == null) {
//            throw exception(CUSTOMER_NOT_EXISTS);
        }
    }

    
    public CustomerDO getCustomer(Long id) {
        return customerMapper.selectById(id);
    }

    
    public List<CustomerDO> getCustomerList(Collection<Long> ids) {
        return customerMapper.selectBatchIds(ids);
    }

    
    public PageResult<CustomerDO> getCustomerPage(CustomerPageReqVO pageReqVO) {
        return customerMapper.selectPage(pageReqVO);
    }

    
    public List<CustomerDO> getCustomerList(CustomerExportReqVO exportReqVO) {
        return customerMapper.selectList(exportReqVO);
    }

    @Resource
    private OAuth2TokenApi oAuth2TokenApi;

    
    public OAuth2AccessTokenRespDTO createAccessToken(String openId) {
        CustomerDO customerDO = customerMapper.selectOne("openid", openId);
        if (customerDO==null){
            throw exception(CUSTOMER_NOT_EXISTS);
        };
        OAuth2AccessTokenCreateReqDTO reqDTO = new OAuth2AccessTokenCreateReqDTO();
        reqDTO.setUserId(customerDO.getId());
        reqDTO.setUserType(UserTypeEnum.MEMBER.getValue());
        reqDTO.setClientId(OAuth2ClientConstants.CLIENT_ID_DEFAULT);
        return oAuth2TokenApi.createAccessToken(reqDTO);
    }


    //todo 一块钱需要1积分,需求待定
    public void updateIntegral(String openid,BigDecimal orderMoney) {
        CustomerDO customerDO = customerMapper.selectOne("openid", openid);
        double moneyToIntegral = orderMoney.multiply(new BigDecimal("1")).doubleValue();
        double result = customerDO.getIntegral() - moneyToIntegral;
        if (result < 0) {
            throw new RuntimeException("积分不够抵扣");
        }
        customerDO.setIntegral(result);
        customerMapper.updateById(customerDO);
    }

    public void updateIntegral2(String openid, BigDecimal money,Double integral) {
        CustomerDO customerDO = customerMapper.selectOne("openid", openid);
        BigDecimal subtract = customerDO.getMoney().subtract(money);
        if (subtract.compareTo(BigDecimal.ZERO) < 0) {
            throw new RuntimeException("余额不够抵扣");
        }
        customerDO.setMoney(subtract).setIntegral(customerDO.getIntegral() + integral);
        customerMapper.updateById(customerDO);
    }

    public void updateIntegral3(String openid, Double integral) {
        CustomerDO customerDO = customerMapper.selectOne("openid", openid);
        customerDO.setIntegral(customerDO.getIntegral() + integral);
        customerMapper.updateById(customerDO);
    }
}
